#include "MeasurementControlWidget.h"
#include "ui_MeasurementControlWidget.h"
#include "MeasurementAlgorithmButton.h"
#include "MeasurementAlgorithmBase.h"
#include <QDebug>
#include <QVBoxLayout>
#include <QPushButton>

MeasurementControlWidget::MeasurementControlWidget(MeasurementAlgorithmManager *pMeasurementAlgorithmManager, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MeasurementControlWidget),
    m_algorithmButtonGroup(new QButtonGroup(this)),
    m_shapeButtonGroup(new QButtonGroup(this)),
    m_pMeasurementAlgorithmManager(pMeasurementAlgorithmManager),
    m_registeredToolWidget(nullptr)
{
    ui->setupUi(this);

    // 初始化按钮组
    m_algorithmButtonGroup->setExclusive(true);
    m_shapeButtonGroup->setExclusive(true);

    // 添加形状按钮到按钮组
    m_shapeButtonGroup->addButton(ui->horizontalPushButton, Horizontal);
    m_shapeButtonGroup->addButton(ui->verticalPushButton, Vertical);
    m_shapeButtonGroup->addButton(ui->rectanglePushButton, Rectangle);

    // 初始设置测量方式按钮为禁用状态
    ui->horizontalPushButton->setDisabled(true);
    ui->verticalPushButton->setDisabled(true);
    ui->rectanglePushButton->setDisabled(true);
    
    // 连接测量方式按钮的信号和槽
    connect(ui->horizontalPushButton, &QPushButton::toggled, this, &MeasurementControlWidget::onMeasurementModeButtonChecked);
    connect(ui->verticalPushButton, &QPushButton::toggled, this, &MeasurementControlWidget::onMeasurementModeButtonChecked);
    connect(ui->rectanglePushButton, &QPushButton::toggled, this, &MeasurementControlWidget::onMeasurementModeButtonChecked);


    // 初始设置所有算法按钮为禁用状态
    enableAllAlgorithmButtons(false);
}

MeasurementControlWidget::~MeasurementControlWidget()
{
    delete ui;
}

void MeasurementControlWidget::addMeasurementAlgorithmButton(const QString &algorithmName, const QString &iconPath)
{
    // 创建新的测量算法按钮
    MeasurementAlgorithmButton *button = new MeasurementAlgorithmButton(ui->scrollAreaWidgetContents);
    // 连接信号和槽
    connect(button, &MeasurementAlgorithmButton::toggled,this, &MeasurementControlWidget::onAlgorithmButtonCheckedChange);

    button->setText(algorithmName);

    // 如果提供了图标路径，设置图标
    if (!iconPath.isEmpty()) {
        button->setIcon(iconPath);
    }

    // 设置按钮属性
    button->setCheckable(true);
    button->setFixedHeight(40);

    // 将按钮添加到按钮组
    m_algorithmButtonGroup->addButton(button);

    // 存储按钮
    m_algorithmButtons[algorithmName] = button;

    // 将按钮添加到布局中（在拉伸项之前）
    ui->verticalLayout_MeasurementAlgorithm->insertWidget(ui->verticalLayout_MeasurementAlgorithm->count() - 1, button);

    // 设置按钮初始状态为禁用
    button->setDisabled(true);
}

void MeasurementControlWidget::enableAllAlgorithmButtons(bool enable)
{
    // 遍历所有算法按钮并设置启用/禁用状态
    for (auto it = m_algorithmButtons.constBegin(); it != m_algorithmButtons.constEnd(); ++it) {
        MeasurementAlgorithmButton *button = it.value();
        if (button) {
            button->setEnabled(enable);
        }
    }
}

void MeasurementControlWidget::onAlgorithmButtonCheckedChange(bool checked)
{
    // 获取当前选中的按钮
    QAbstractButton *checkedButton = (QAbstractButton *)sender();
    // 查找选中按钮对应的算法名称
    QString algorithmName;
    for (auto it = m_algorithmButtons.constBegin(); it != m_algorithmButtons.constEnd(); ++it) {
        if (it.value() == checkedButton) {
            algorithmName = it.key();
            break;
        }
    }
    // 如果有选中的按钮，根据算法支持的测量类型显示相应的测量方式按钮
    if (checked&&checkedButton)
    {
        // 获取该算法支持的测量模式
        MeasurementModes supportedModes = m_pMeasurementAlgorithmManager->getSupportedModes(algorithmName);

        // 检查是否支持横向测量（包含横线单线或横线双线测量）
        bool supportsHorizontal = supportedModes.testFlag(MeasurementMode::HorizontalSingleLine) || 
                                 supportedModes.testFlag(MeasurementMode::HorizontalDoubleLine);
        
        // 检查是否支持纵向测量（包含纵线单线或纵线双线测量）
        bool supportsVertical = supportedModes.testFlag(MeasurementMode::VerticalSingleLine) || 
                               supportedModes.testFlag(MeasurementMode::VerticalDoubleLine);
        
        // 检查是否支持矩形区域测量
        bool supportsRectangle = supportedModes.testFlag(MeasurementMode::RectangleRegion);

        // 根据支持的测量模式设置按钮的启用状态
        ui->horizontalPushButton->setEnabled(supportsHorizontal);
        ui->verticalPushButton->setEnabled(supportsVertical);
        ui->rectanglePushButton->setEnabled(supportsRectangle);

        //回复模式按钮状态
        QPushButton *modeButton =qobject_cast<QPushButton*>(m_shapeButtonGroup->checkedButton());
        if(modeButton)
        {
            m_shapeButtonGroup->setExclusive(false);
            modeButton->setChecked(false);
            m_shapeButtonGroup->setExclusive(true);
        }
    }
    else if(!checked)
    {
        m_pMeasurementAlgorithmManager->endProcessMeasurement(algorithmName);
    }
    else
    {
        ui->horizontalPushButton->setEnabled(false);
        ui->verticalPushButton->setEnabled(false);
        ui->rectanglePushButton->setEnabled(false);

    }
}

void MeasurementControlWidget:: onMeasurementModeButtonChecked(bool checked)
{
    if (checked)
    {
        // 获取当前的算法按钮
        QAbstractButton *checkedButton = m_algorithmButtonGroup->checkedButton();
        if (!checkedButton)
        {
            return;
        }
        // 查找算法名称
        QString algorithmName;
        for (auto it = m_algorithmButtons.constBegin(); it != m_algorithmButtons.constEnd(); ++it) {
            if (it.value() == checkedButton) {
                algorithmName = it.key();
                break;
            }
        }
        // 创建参数映射
        QVariantMap parameters;
        // 获取发送信号的按钮
        QPushButton *senderButton = qobject_cast<QPushButton*>(sender());
        // 获取算法支持的测量模式
        MeasurementModes supportedModes = m_pMeasurementAlgorithmManager->getSupportedModes(algorithmName);
        // 根据按钮和算法支持的模式确定具体的测量类型
        if (senderButton == ui->horizontalPushButton) {
            // 对于横向测量，优先使用单线模式，如果不支持则使用双线模式
            if (supportedModes.testFlag(MeasurementMode::HorizontalSingleLine)) {
                parameters["measurementType"] = "HorizontalSingleLine";
            } else if (supportedModes.testFlag(MeasurementMode::HorizontalDoubleLine)) {
                parameters["measurementType"] = "HorizontalDoubleLine";
            }
        } else if (senderButton == ui->verticalPushButton) {
            // 对于纵向测量，优先使用单线模式，如果不支持则使用双线模式
            if (supportedModes.testFlag(MeasurementMode::VerticalSingleLine)) {
                parameters["measurementType"] = "VerticalSingleLine";
            } else if (supportedModes.testFlag(MeasurementMode::VerticalDoubleLine)) {
                parameters["measurementType"] = "VerticalDoubleLine";
            }
        } else if (senderButton == ui->rectanglePushButton) {
            // 对于矩形测量，直接使用矩形区域模式
            if (supportedModes.testFlag(MeasurementMode::RectangleRegion)) {
                parameters["measurementType"] = "RectangleRegion";
            }
        }

        // 只有当测量类型参数已设置时才发送请求
        if (parameters.contains("measurementType")) {
            emit measurementImageRequested(algorithmName, parameters);
        }
    }
}

void MeasurementControlWidget::registerMeasurementToolWidget(QWidget* toolWidget)
{
    // 如果已经注册了工具，先清理
    if (m_registeredToolWidget) {
        restoreDefaultMeasurementTools();
    }
    
    if (toolWidget) {
        // 获取测量工具按钮所在的布局
        QHBoxLayout* layout = ui->horizontalLayout_2;
        
        // 隐藏默认的测量按钮widget
        ui->measuementToolWidget->hide();
        
        // 将自定义工具widget添加到布局中
        layout->insertWidget(0,toolWidget);
        
        // 保存工具widget的引用
        m_registeredToolWidget = toolWidget;
        
        // 确保新添加的widget可见
        toolWidget->show();
    }
}

void MeasurementControlWidget::restoreDefaultMeasurementTools()
{
    // 如果有注册的自定义工具，从布局中移除它
    if (m_registeredToolWidget) {
        QHBoxLayout* layout = ui->horizontalLayout_2;
        layout->removeWidget(m_registeredToolWidget);
        
        // 不需要删除widget，因为我们只是负责布局管理，所有权应该在调用者
        m_registeredToolWidget = nullptr;
    }
    
    // 显示默认的测量按钮widget
    ui->measuementToolWidget->show();
}

void MeasurementControlWidget::setMeasurementAlgorithmButtonSelected(const QString &algorithmName, bool selected)
{
    // 检查算法名称是否存在于按钮映射中
    if (!m_algorithmButtons.contains(algorithmName))
    {
        qWarning() << "Measurement algorithm button not found: " << algorithmName;
    }
    MeasurementAlgorithmButton *button = m_algorithmButtons[algorithmName];
    if (!button)
    {
        qDebug() << "measurement algorithm button '" << algorithmName << "' not found:" << selected;
    }
    disconnect(button, &MeasurementAlgorithmButton::toggled,this, &MeasurementControlWidget::onAlgorithmButtonCheckedChange);
    // 设置按钮选中状态
    button->setChecked(selected);
    connect(button, &MeasurementAlgorithmButton::toggled,this, &MeasurementControlWidget::onAlgorithmButtonCheckedChange);
}
